﻿using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Newtonsoft.Json.Linq;
using Tuna.Revit.Extension;
namespace RevitCopilot.Commands;
public class DeleteElementsCommand : ExternalEventCommandBase
{
    public DeleteElementsCommand(UIApplication app) : base(app) { }
    public override string CommandName => "DeleteElementsCommand";
    public override string Execute(JObject parameters, string requestId)
    {
        string[]? elementIds = parameters["elementIds"]?.ToObject<string[]>();
        if (elementIds == null || elementIds.Length == 0)
        {
            return "方法执行错误：elementIds参数为空或未提供";
        }
        int successCount = 0;
        int failCount = 0;
        List<string> failedReasons = new List<string>();
        try
        {
            TransactionResult result = Doc.NewTransaction(() =>
            {
                foreach (string idString in elementIds)
                {
                    if (!int.TryParse(idString, out int idValue))
                    {
                        failCount++;
                        failedReasons.Add($"ID格式无效: {idString}");
                        continue;
                    }
                    ElementId elementId = new ElementId(idValue);
                    Element? element = Doc.GetElement(elementId);
                    if (element == null)
                    {
                        failCount++;
                        failedReasons.Add($"元素不存在: {idString}");
                        continue;
                    }
                    ICollection<ElementId> deletedIds = Doc.Delete(elementId);
                    if (deletedIds != null && deletedIds.Count > 0)
                    {
                        successCount++;
                    }
                    else
                    {
                        failCount++;
                        failedReasons.Add($"删除失败: {idString}");
                    }
                }
            }, "通过ID删除元素");
            // 结果汇总（与之前相同）
            string summary = $"操作完成：成功删除 {successCount} 个元素，失败 {failCount} 个";
            if (failedReasons.Count > 0)
            {
                summary += $"\n失败详情:\n{string.Join("\n", failedReasons.Take(5))}";
                if (failedReasons.Count > 5) summary += "\n...（更多错误已省略）";
            }
            return summary;
        }
        catch (Exception ex)
        {
            return $"系统异常: {ex.Message}\n部分执行结果：成功 {successCount} 个，失败 {failCount} 个";
        }
    }
}